var models = require('../db');
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var $sql = require('../sqlMap');

// 连接数据库
var conn = mysql.createConnection(models.mysql);

conn.connect();
var jsonWrite = function(res, ret) {
    if(typeof ret === 'undefined') {
        res.json({
            code: '1',
            msg: '操作失败'
        });
    } else {
        res.json(ret);
    }
};

router.use('/selectCount',(req,res)=>{
    var sql = $sql.user.selectCount;  
    conn.query(sql,function(err, result) { 
        if (err) {       
            console.log(err);
        }        
        if (result) {
            jsonWrite(res, result);
        }
    })
})
//查询学生数据
router.use('/selectStudent', (req, res) => {
    var sql = $sql.user.selectStudent;   
    var params = req.body;
    conn.query(sql,[params.start,params.end],function(err, result) { 
        if (err) {       
            console.log(err);
        }        
        if (result) {
            jsonWrite(res, result);
        }
    })


});

//删除学生数据
router.use('/deleteStudent', (req, res) => {
    var sql = $sql.user.deleteStudent;   
    var params = req.body; 
    conn.query(sql,[params.id],function(err, result) {    
        if (err) {       
            console.log(err);
        }        
        if (result) {
            jsonWrite(res, result);
        }
    })
});



//登陆
router.use('/selectUser', (req, res) => {
    var sql = $sql.user.selectUser;    
    var params = req.body;
    conn.query(sql,[params.userName,params.userPwd],function(err, result) {    
        if (err) {       
            console.log(err);
        }        
        if (result) {
            var sql="SELECT * FROM user where userName = ?";
            conn.query(sql,[params.userName],(err,result)=>{
                if(result==""||result==null){
                        res.send({code:0,msg:"找不到用户名"});
                   }else{
                       var oldPass=result[0].userPwd;
                       if(params.userPwd==oldPass){
                            res.send({code:1,msg:"登录成功"})
                       }else{
                           res.send({code: 0,msg:"密码不对"});
                       }  
                }
            });   
        }
    })
});


module.exports = router;
